<!DOCTYPE html>
<html lang="zh-CN">
    <head>
        <meta charset="utf-8">
        <meta name="viewport" content="width=device-width, initial-scale=1">
        <meta name="robots" content="noodp" />
        <title>Java网络编程 - L_B__</title><meta name="referrer" content="no-referrer">
<meta name="description" content="Java网络编程"><meta property="og:title" content="Java网络编程" />
<meta property="og:description" content="Java网络编程" />
<meta property="og:type" content="article" />
<meta property="og:url" content="https://acking-you.github.io/posts/java%E7%BD%91%E7%BB%9C%E7%BC%96%E7%A8%8B/" /><meta property="og:image" content="https://acking-you.github.io/logo.png"/><meta property="article:section" content="posts" />
<meta property="article:published_time" content="2022-01-26T00:00:00+00:00" />
<meta property="article:modified_time" content="2022-01-26T00:00:00+00:00" />

<meta name="twitter:card" content="summary_large_image"/>
<meta name="twitter:image" content="https://acking-you.github.io/logo.png"/>

<meta name="twitter:title" content="Java网络编程"/>
<meta name="twitter:description" content="Java网络编程"/>
<meta name="application-name" content="FeelIt">
<meta name="apple-mobile-web-app-title" content="FeelIt"><meta name="theme-color" content="#ffffff"><meta name="msapplication-TileColor" content="#da532c"><link rel="canonical" href="https://acking-you.github.io/posts/java%E7%BD%91%E7%BB%9C%E7%BC%96%E7%A8%8B/" /><link rel="prev" href="https://acking-you.github.io/posts/tcp%E7%BD%91%E7%BB%9C%E7%BC%96%E7%A8%8B%E4%B8%ADconnectlistenaccept%E4%B8%89%E8%80%85%E4%B9%8B%E9%97%B4%E7%9A%84%E5%85%B3%E7%B3%BB/" /><link rel="next" href="https://acking-you.github.io/posts/leetcode%E6%AF%8F%E6%97%A5%E4%B8%80%E9%A2%98-%E6%A3%80%E6%B5%8B%E6%AD%A3%E6%96%B9%E5%BD%A2/" /><link rel="stylesheet" href="/css/page.min.css"><link rel="stylesheet" href="/css/home.min.css"><script type="application/ld+json">
    {
        "@context": "http://schema.org",
        "@type": "BlogPosting",
        "headline": "Java网络编程",
        "inLanguage": "zh-CN",
        "mainEntityOfPage": {
            "@type": "WebPage",
            "@id": "https:\/\/acking-you.github.io\/posts\/java%E7%BD%91%E7%BB%9C%E7%BC%96%E7%A8%8B\/"
        },"genre": "posts","keywords": "JavaWeb第一节","wordcount":  4973 ,
        "url": "https:\/\/acking-you.github.io\/posts\/java%E7%BD%91%E7%BB%9C%E7%BC%96%E7%A8%8B\/","datePublished": "2022-01-26T00:00:00+00:00","dateModified": "2022-01-26T00:00:00+00:00","publisher": {
            "@type": "Organization",
            "name": "作者"},"author": {
                "@type": "Person",
                "name": "作者"
            },"description": "Java网络编程"
    }
    </script></head><body data-header-desktop="auto" data-header-mobile="auto"><script>(window.localStorage && localStorage.getItem('theme') ? localStorage.getItem('theme') === 'dark' : ('auto' === 'auto' ? window.matchMedia('(prefers-color-scheme: dark)').matches : 'auto' === 'dark')) && document.body.setAttribute('theme', 'dark');</script>

        <div id="mask"></div><div class="wrapper"><header class="desktop" id="header-desktop">
    <div class="header-wrapper">
        <div class="header-title">
            <a href="/" title="L_B__">L_B__</a>
        </div>
        <div class="menu">
            <div class="menu-inner"><a class="menu-item" href="/posts/"> 文章 </a><a class="menu-item" href="/tags/"> 标签 </a><a class="menu-item" href="/categories/"> 分类 </a><span class="menu-item delimiter"></span><span class="menu-item search" id="search-desktop">
                        <input type="text" placeholder="搜索文章标题或内容..." id="search-input-desktop">
                        <a href="#" class="search-button search-toggle" id="search-toggle-desktop" title="搜索">
                            <i class="fas fa-search fa-fw"></i>
                        </a>
                        <a href="#" class="search-button search-clear" id="search-clear-desktop" title="清空">
                            <i class="fas fa-times-circle fa-fw"></i>
                        </a>
                        <span class="search-button search-loading" id="search-loading-desktop">
                            <i class="fas fa-spinner fa-fw fa-spin"></i>
                        </span>
                    </span><a href="javascript:void(0);" class="menu-item theme-switch" title="切换主题">
                    <i class="fas fa-adjust fa-fw"></i>
                </a>
            </div>
        </div>
    </div>
</header><header class="mobile" id="header-mobile">
    <div class="header-container">
        <div class="header-wrapper">
            <div class="header-title">
                <a href="/" title="L_B__">L_B__</a>
            </div>
            <div class="menu-toggle" id="menu-toggle-mobile">
                <span></span><span></span><span></span>
            </div>
        </div>
        <div class="menu" id="menu-mobile"><div class="search-wrapper">
                    <div class="search mobile" id="search-mobile">
                        <input type="text" placeholder="搜索文章标题或内容..." id="search-input-mobile">
                        <a href="#" class="search-button search-toggle" id="search-toggle-mobile" title="搜索">
                            <i class="fas fa-search fa-fw"></i>
                        </a>
                        <a href="#" class="search-button search-clear" id="search-clear-mobile" title="清空">
                            <i class="fas fa-times-circle fa-fw"></i>
                        </a>
                        <span class="search-button search-loading" id="search-loading-mobile">
                            <i class="fas fa-spinner fa-fw fa-spin"></i>
                        </span>
                    </div>
                    <a href="#" class="search-cancel" id="search-cancel-mobile">
                        取消
                    </a>
                </div><a class="menu-item" href="/posts/" title="">文章</a><a class="menu-item" href="/tags/" title="">标签</a><a class="menu-item" href="/categories/" title="">分类</a><div class="menu-item"><a href="javascript:void(0);" class="theme-switch" title="切换主题">
                    <i class="fas fa-adjust fa-fw"></i>
                </a>
            </div></div>
    </div>
</header><div class="search-dropdown desktop">
    <div id="search-dropdown-desktop"></div>
</div>
<div class="search-dropdown mobile">
    <div id="search-dropdown-mobile"></div>
</div><main class="main">
                <div class="container"><div class="toc" id="toc-auto">
            <h2 class="toc-title">目录</h2>
            <div class="toc-content" id="toc-content-auto"></div>
        </div><article class="page single" data-toc="disable"><div class="featured-image"><img
        class="lazyload"
        src="/svg/loading.min.svg"
        data-src="https://s4.ax1x.com/2022/01/22/7hWvAH.png"
        data-srcset="https://s4.ax1x.com/2022/01/22/7hWvAH.png, https://s4.ax1x.com/2022/01/22/7hWvAH.png 1.5x, https://s4.ax1x.com/2022/01/22/7hWvAH.png 2x"
        data-sizes="auto"
        alt="https://s4.ax1x.com/2022/01/22/7hWvAH.png"
        title="Java网络编程" /></div><div class="single-card" data-image="true"><h2 class="single-title animated flipInX">Java网络编程</h2><div class="post-meta">
                <div class="post-meta-line"><span class="post-author"><a href="/" title="Author" rel=" author" class="author"><i class="fas fa-user-circle fa-fw"></i>作者</a></span>&nbsp;<span class="post-category">出版于  <a href="/categories/javaweb%E7%AC%94%E8%AE%B0/"><i class="far fa-folder fa-fw"></i>JavaWeb笔记</a></span></div>
                <div class="post-meta-line"><span><i class="far fa-calendar-alt fa-fw"></i>&nbsp;<time datetime="2022-01-26">2022-01-26</time></span>&nbsp;<span><i class="fas fa-pencil-alt fa-fw"></i>&nbsp;约 4973 字</span>&nbsp;
                    <span><i class="far fa-clock fa-fw"></i>&nbsp;预计阅读 10 分钟</span>&nbsp;</div>
            </div>
            
            <hr><div class="details toc" id="toc-static"  data-kept="">
                    <div class="details-summary toc-title">
                        <span>目录</span>
                        <span><i class="details-icon fas fa-angle-right"></i></span>
                    </div>
                    <div class="details-content toc-content" id="toc-content-static"><nav id="TableOfContents">
  <ul>
    <li><a href="#计算机网络基础">计算机网络基础</a></li>
    <li><a href="#了解socket技术">了解Socket技术</a></li>
    <li><a href="#使用socket进行数据传输">使用Socket进行数据传输</a></li>
    <li><a href="#使用socket传输文件">使用Socket传输文件</a></li>
    <li><a href="#使用浏览器访问socket服务器">使用浏览器访问Socket服务器</a></li>
  </ul>
</nav></div>
                </div><div class="content" id="content"><h1 id="java网络编程">Java网络编程</h1>
<p><a href="https://www.bilibili.com/video/BV1CL4y1i7qR?p=3" target="_blank" rel="noopener noreffer">配套视频</a></p>
<p>在JavaSE阶段，我们学习了I/O流，既然I/O流如此强大，那么能否跨越不同的主机进行I/O操作呢？这就要提到Java的网络编程了。</p>
<p><strong>注意</strong>：本章会涉及到<code>计算机网络</code>相关内容（只会讲解大致内容，不会完整的讲解计算机网络知识）</p>
<blockquote>
<p>若没有计算机网络基础，实际上Java这里封装的Socket网络IO操作已经简单到完全不需要任何基础的，但是没有计算机网络相关的底层知识，以后的深入学习会非常不知所云。</p>
</blockquote>
<h2 id="计算机网络基础">计算机网络基础</h2>
<p>利用通信线路和通信设备，将地理位置不同的、功能独立的多台计算机互连起来，以功能完善的网络软件来实现资源共享和信息传递，就构成了计算机网络系统。</p>
<p><img
        class="lazyload"
        src="/svg/loading.min.svg"
        data-src="https://s2.loli.net/2022/01/26/njH76zQNX5yGhxs.jpg"
        data-srcset="https://s2.loli.net/2022/01/26/njH76zQNX5yGhxs.jpg, https://s2.loli.net/2022/01/26/njH76zQNX5yGhxs.jpg 1.5x, https://s2.loli.net/2022/01/26/njH76zQNX5yGhxs.jpg 2x"
        data-sizes="auto"
        alt="https://s2.loli.net/2022/01/26/njH76zQNX5yGhxs.jpg"
        title="https://s2.loli.net/2022/01/26/njH76zQNX5yGhxs.jpg" /></p>
<p>比如我们家里的路由器，通过将我们的设备（手机、平板、电脑、电视剧）连接到路由器，来实现对互联网的访问。实际上，我们的路由器连接在互联网上，而我们的设备又连接了路由器，这样我们的设备就可以通过路由器访问到互联网了。通过网络，我们可以直接访问互联网上的另一台主机，比如我们要把QQ的消息发送给我们的朋友，或是通过远程桌面管理来操作另一台电脑，也可以是连接本地网络上的打印机。</p>
<p>既然我们可以通过网络访问其他计算机，那么如何区别不同的计算机呢？通过IP地址，我们就可以区分不同的计算机了：</p>
<p><img
        class="lazyload"
        src="/svg/loading.min.svg"
        data-src="https://gimg2.baidu.com/image_search/src=http%3A%2F%2Fimg.it610.com%2Fimage%2Finfo5%2Facf4321f34144b69811bdde9bec045c8.jpg&amp;refer=http%3A%2F%2Fimg.it610.com&amp;app=2002&amp;size=f9999,10000&amp;q=a80&amp;n=0&amp;g=0n&amp;fmt=jpeg?sec=1637820816&amp;t=955be58edb486e7a69cdea2381714252"
        data-srcset="https://gimg2.baidu.com/image_search/src=http%3A%2F%2Fimg.it610.com%2Fimage%2Finfo5%2Facf4321f34144b69811bdde9bec045c8.jpg&amp;refer=http%3A%2F%2Fimg.it610.com&amp;app=2002&amp;size=f9999%2c10000&amp;q=a80&amp;n=0&amp;g=0n&amp;fmt=jpeg?sec=1637820816&amp;t=955be58edb486e7a69cdea2381714252, https://gimg2.baidu.com/image_search/src=http%3A%2F%2Fimg.it610.com%2Fimage%2Finfo5%2Facf4321f34144b69811bdde9bec045c8.jpg&amp;refer=http%3A%2F%2Fimg.it610.com&amp;app=2002&amp;size=f9999%2c10000&amp;q=a80&amp;n=0&amp;g=0n&amp;fmt=jpeg?sec=1637820816&amp;t=955be58edb486e7a69cdea2381714252 1.5x, https://gimg2.baidu.com/image_search/src=http%3A%2F%2Fimg.it610.com%2Fimage%2Finfo5%2Facf4321f34144b69811bdde9bec045c8.jpg&amp;refer=http%3A%2F%2Fimg.it610.com&amp;app=2002&amp;size=f9999%2c10000&amp;q=a80&amp;n=0&amp;g=0n&amp;fmt=jpeg?sec=1637820816&amp;t=955be58edb486e7a69cdea2381714252 2x"
        data-sizes="auto"
        alt="https://gimg2.baidu.com/image_search/src=http%3A%2F%2Fimg.it610.com%2Fimage%2Finfo5%2Facf4321f34144b69811bdde9bec045c8.jpg&amp;refer=http%3A%2F%2Fimg.it610.com&amp;app=2002&amp;size=f9999,10000&amp;q=a80&amp;n=0&amp;g=0n&amp;fmt=jpeg?sec=1637820816&amp;t=955be58edb486e7a69cdea2381714252"
        title="img" /></p>
<p>每一台电脑在同一个网络上都有一个自己的IP地址，用于区别于其他的电脑，我们可以通过对方主机的IP地址对其进行访问。那么我手机连接的移动流量，能访问到连接家里路由器的电脑吗？（不能，因为他们不属于同一个网络）</p>
<p>而我们的电脑上可能运行着大量的程序，每一个程序可能都需要通过网络来访问其他计算机，那这时该如何区分呢？我们可以通过端口号来区分：</p>
<p><img
        class="lazyload"
        src="/svg/loading.min.svg"
        data-src="https://gimg2.baidu.com/image_search/src=http%3A%2F%2Fimg2020.cnblogs.com%2Fblog%2F2068098%2F202008%2F2068098-20200808153937940-609503998.png&amp;refer=http%3A%2F%2Fimg2020.cnblogs.com&amp;app=2002&amp;size=f9999,10000&amp;q=a80&amp;n=0&amp;g=0n&amp;fmt=jpeg?sec=1637821431&amp;t=9dfd5db6c6f75f843d1663f54b2ccb6c"
        data-srcset="https://gimg2.baidu.com/image_search/src=http%3A%2F%2Fimg2020.cnblogs.com%2Fblog%2F2068098%2F202008%2F2068098-20200808153937940-609503998.png&amp;refer=http%3A%2F%2Fimg2020.cnblogs.com&amp;app=2002&amp;size=f9999%2c10000&amp;q=a80&amp;n=0&amp;g=0n&amp;fmt=jpeg?sec=1637821431&amp;t=9dfd5db6c6f75f843d1663f54b2ccb6c, https://gimg2.baidu.com/image_search/src=http%3A%2F%2Fimg2020.cnblogs.com%2Fblog%2F2068098%2F202008%2F2068098-20200808153937940-609503998.png&amp;refer=http%3A%2F%2Fimg2020.cnblogs.com&amp;app=2002&amp;size=f9999%2c10000&amp;q=a80&amp;n=0&amp;g=0n&amp;fmt=jpeg?sec=1637821431&amp;t=9dfd5db6c6f75f843d1663f54b2ccb6c 1.5x, https://gimg2.baidu.com/image_search/src=http%3A%2F%2Fimg2020.cnblogs.com%2Fblog%2F2068098%2F202008%2F2068098-20200808153937940-609503998.png&amp;refer=http%3A%2F%2Fimg2020.cnblogs.com&amp;app=2002&amp;size=f9999%2c10000&amp;q=a80&amp;n=0&amp;g=0n&amp;fmt=jpeg?sec=1637821431&amp;t=9dfd5db6c6f75f843d1663f54b2ccb6c 2x"
        data-sizes="auto"
        alt="https://gimg2.baidu.com/image_search/src=http%3A%2F%2Fimg2020.cnblogs.com%2Fblog%2F2068098%2F202008%2F2068098-20200808153937940-609503998.png&amp;refer=http%3A%2F%2Fimg2020.cnblogs.com&amp;app=2002&amp;size=f9999,10000&amp;q=a80&amp;n=0&amp;g=0n&amp;fmt=jpeg?sec=1637821431&amp;t=9dfd5db6c6f75f843d1663f54b2ccb6c"
        title="img" /></p>
<p>因此，我们一般看到的是这样的：<code>192.168.0.11:8080</code>，通过<code>IP:端口</code>的形式来访问目标主机上的一个应用程序服务。注意端口号只能是0-65535之间的值！</p>
<p>IP地址分为IPv4和IPv6，IPv4类似于<code>192.168.0.11</code>，我们上面提到的例子都是使用的IPv4，它一共有四组数字，每组数字占8个bit位，IPv4地址<code>0.0.0.0</code>表示为2进制就是：00000000.00000000.00000000.00000000，共32个bit，最大为<code>255.255.255.255</code>，实际上，IPv4能够表示的所有地址，早就已经被用完了。IPv6能够保存128个bit位，因此它也可以表示更多的IP地址，一个IPv6地址看起来像这样：<code>1030::C9B4:FF12:48AA:1A2B</code>，目前也正在向IPv6的阶段过度。</p>
<p>TCP和UDP是两种不同的传输层协议：</p>
<ul>
<li>TCP：当一台计算机想要与另一台计算机通讯时，两台计算机之间的通信需要畅通且可靠（会进行三次握手，断开也会进行四次挥手），这样才能保证正确收发数据，因此TCP更适合一些可靠的数据传输场景。</li>
<li>UDP：它是一种无连接协议，数据想发就发，而且不会建立可靠传输，也就是说传输过程中有可能会导致部分数据丢失，但是它比TCP传输更加简单高效，适合视频直播之类的。</li>
</ul>
<p><img
        class="lazyload"
        src="/svg/loading.min.svg"
        data-src="https://gimg2.baidu.com/image_search/src=http%3A%2F%2F5b0988e595225.cdn.sohucs.com%2Fq_70%2Cc_zoom%2Cw_640%2Fimages%2F20200212%2F0f3d7f77442643c099dddbb159a183f6.jpeg&amp;refer=http%3A%2F%2F5b0988e595225.cdn.sohucs.com&amp;app=2002&amp;size=f9999,10000&amp;q=a80&amp;n=0&amp;g=0n&amp;fmt=jpeg?sec=1637824557&amp;t=b5d5cb0c013ae945e838e88a345edb9c"
        data-srcset="https://gimg2.baidu.com/image_search/src=http%3A%2F%2F5b0988e595225.cdn.sohucs.com%2Fq_70%2Cc_zoom%2Cw_640%2Fimages%2F20200212%2F0f3d7f77442643c099dddbb159a183f6.jpeg&amp;refer=http%3A%2F%2F5b0988e595225.cdn.sohucs.com&amp;app=2002&amp;size=f9999%2c10000&amp;q=a80&amp;n=0&amp;g=0n&amp;fmt=jpeg?sec=1637824557&amp;t=b5d5cb0c013ae945e838e88a345edb9c, https://gimg2.baidu.com/image_search/src=http%3A%2F%2F5b0988e595225.cdn.sohucs.com%2Fq_70%2Cc_zoom%2Cw_640%2Fimages%2F20200212%2F0f3d7f77442643c099dddbb159a183f6.jpeg&amp;refer=http%3A%2F%2F5b0988e595225.cdn.sohucs.com&amp;app=2002&amp;size=f9999%2c10000&amp;q=a80&amp;n=0&amp;g=0n&amp;fmt=jpeg?sec=1637824557&amp;t=b5d5cb0c013ae945e838e88a345edb9c 1.5x, https://gimg2.baidu.com/image_search/src=http%3A%2F%2F5b0988e595225.cdn.sohucs.com%2Fq_70%2Cc_zoom%2Cw_640%2Fimages%2F20200212%2F0f3d7f77442643c099dddbb159a183f6.jpeg&amp;refer=http%3A%2F%2F5b0988e595225.cdn.sohucs.com&amp;app=2002&amp;size=f9999%2c10000&amp;q=a80&amp;n=0&amp;g=0n&amp;fmt=jpeg?sec=1637824557&amp;t=b5d5cb0c013ae945e838e88a345edb9c 2x"
        data-sizes="auto"
        alt="https://gimg2.baidu.com/image_search/src=http%3A%2F%2F5b0988e595225.cdn.sohucs.com%2Fq_70%2Cc_zoom%2Cw_640%2Fimages%2F20200212%2F0f3d7f77442643c099dddbb159a183f6.jpeg&amp;refer=http%3A%2F%2F5b0988e595225.cdn.sohucs.com&amp;app=2002&amp;size=f9999,10000&amp;q=a80&amp;n=0&amp;g=0n&amp;fmt=jpeg?sec=1637824557&amp;t=b5d5cb0c013ae945e838e88a345edb9c"
        title="img" /></p>
<hr>
<h2 id="了解socket技术">了解Socket技术</h2>
<p>通过Socket技术（它是计算机之间进行<strong>通信</strong>的<strong>一种约定</strong>或一种方式），我们就可以实现两台计算机之间的通信，Socket也被翻译为<code>套接字</code>，是操作系统底层提供的一项通信技术，它支持TCP和UDP。而Java就对socket底层支持进行了一套完整的封装，我们可以通过Java来实现Socket通信。</p>
<p>要实现Socket通信，我们必须创建一个数据发送者和一个数据接收者，也就是客户端和服务端，我们需要提前启动服务端，来等待客户端的连接，而客户端只需要随时启动去连接服务端即可！</p>
<div class="highlight"><pre tabindex="0" class="chroma"><code class="language-java" data-lang="java"><span class="c1">//服务端
</span><span class="c1"></span><span class="kd">public</span> <span class="kd">static</span> <span class="kt">void</span> <span class="nf">main</span><span class="o">(</span><span class="n">String</span><span class="o">[]</span> <span class="n">args</span><span class="o">)</span> <span class="o">{</span>
    <span class="k">try</span><span class="o">(</span><span class="n">ServerSocket</span> <span class="n">server</span> <span class="o">=</span> <span class="k">new</span> <span class="n">ServerSocket</span><span class="o">(</span><span class="n">8080</span><span class="o">)){</span>    <span class="c1">//将服务端创建在端口8080上
</span><span class="c1"></span>        <span class="n">System</span><span class="o">.</span><span class="na">out</span><span class="o">.</span><span class="na">println</span><span class="o">(</span><span class="s">&#34;正在等待客户端连接...&#34;</span><span class="o">);</span>
        <span class="n">Socket</span> <span class="n">socket</span> <span class="o">=</span> <span class="n">server</span><span class="o">.</span><span class="na">accept</span><span class="o">();</span>  <span class="c1">//当没有客户端连接时，线程会阻塞，直到有客户端连接为止
</span><span class="c1"></span>        <span class="n">System</span><span class="o">.</span><span class="na">out</span><span class="o">.</span><span class="na">println</span><span class="o">(</span><span class="s">&#34;客户端已连接，IP地址为：&#34;</span><span class="o">+</span><span class="n">socket</span><span class="o">.</span><span class="na">getInetAddress</span><span class="o">().</span><span class="na">getHostAddress</span><span class="o">());</span>
    <span class="o">}</span><span class="k">catch</span> <span class="o">(</span><span class="n">IOException</span> <span class="n">e</span><span class="o">){</span>
        <span class="n">e</span><span class="o">.</span><span class="na">printStackTrace</span><span class="o">();</span>
    <span class="o">}</span>
<span class="o">}</span>
</code></pre></div><div class="highlight"><pre tabindex="0" class="chroma"><code class="language-java" data-lang="java"><span class="c1">//客户端
</span><span class="c1"></span><span class="kd">public</span> <span class="kd">static</span> <span class="kt">void</span> <span class="nf">main</span><span class="o">(</span><span class="n">String</span><span class="o">[]</span> <span class="n">args</span><span class="o">)</span> <span class="o">{</span>
    <span class="k">try</span> <span class="o">(</span><span class="n">Socket</span> <span class="n">socket</span> <span class="o">=</span> <span class="k">new</span> <span class="n">Socket</span><span class="o">(</span><span class="s">&#34;localhost&#34;</span><span class="o">,</span> <span class="n">8080</span><span class="o">)){</span>
        <span class="n">System</span><span class="o">.</span><span class="na">out</span><span class="o">.</span><span class="na">println</span><span class="o">(</span><span class="s">&#34;已连接到服务端！&#34;</span><span class="o">);</span>
    <span class="o">}</span><span class="k">catch</span> <span class="o">(</span><span class="n">IOException</span> <span class="n">e</span><span class="o">){</span>
        <span class="n">System</span><span class="o">.</span><span class="na">out</span><span class="o">.</span><span class="na">println</span><span class="o">(</span><span class="s">&#34;服务端连接失败！&#34;</span><span class="o">);</span>
        <span class="n">e</span><span class="o">.</span><span class="na">printStackTrace</span><span class="o">();</span>
    <span class="o">}</span>
<span class="o">}</span>
</code></pre></div><p>实际上它就是一个TCP连接的建立过程：</p>
<p><img
        class="lazyload"
        src="/svg/loading.min.svg"
        data-src="https://gimg2.baidu.com/image_search/src=http%3A%2F%2Fwww.reader8.cn%2Fuploadfile%2Fjiaocheng%2F201401101%2F3039%2F2014013015391315977.jpg&amp;refer=http%3A%2F%2Fwww.reader8.cn&amp;app=2002&amp;size=f9999,10000&amp;q=a80&amp;n=0&amp;g=0n&amp;fmt=jpeg?sec=1637838562&amp;t=a22f860adb01fda478ecb76f34c34252"
        data-srcset="https://gimg2.baidu.com/image_search/src=http%3A%2F%2Fwww.reader8.cn%2Fuploadfile%2Fjiaocheng%2F201401101%2F3039%2F2014013015391315977.jpg&amp;refer=http%3A%2F%2Fwww.reader8.cn&amp;app=2002&amp;size=f9999%2c10000&amp;q=a80&amp;n=0&amp;g=0n&amp;fmt=jpeg?sec=1637838562&amp;t=a22f860adb01fda478ecb76f34c34252, https://gimg2.baidu.com/image_search/src=http%3A%2F%2Fwww.reader8.cn%2Fuploadfile%2Fjiaocheng%2F201401101%2F3039%2F2014013015391315977.jpg&amp;refer=http%3A%2F%2Fwww.reader8.cn&amp;app=2002&amp;size=f9999%2c10000&amp;q=a80&amp;n=0&amp;g=0n&amp;fmt=jpeg?sec=1637838562&amp;t=a22f860adb01fda478ecb76f34c34252 1.5x, https://gimg2.baidu.com/image_search/src=http%3A%2F%2Fwww.reader8.cn%2Fuploadfile%2Fjiaocheng%2F201401101%2F3039%2F2014013015391315977.jpg&amp;refer=http%3A%2F%2Fwww.reader8.cn&amp;app=2002&amp;size=f9999%2c10000&amp;q=a80&amp;n=0&amp;g=0n&amp;fmt=jpeg?sec=1637838562&amp;t=a22f860adb01fda478ecb76f34c34252 2x"
        data-sizes="auto"
        alt="https://gimg2.baidu.com/image_search/src=http%3A%2F%2Fwww.reader8.cn%2Fuploadfile%2Fjiaocheng%2F201401101%2F3039%2F2014013015391315977.jpg&amp;refer=http%3A%2F%2Fwww.reader8.cn&amp;app=2002&amp;size=f9999,10000&amp;q=a80&amp;n=0&amp;g=0n&amp;fmt=jpeg?sec=1637838562&amp;t=a22f860adb01fda478ecb76f34c34252"
        title="img" /></p>
<p>一旦TCP连接建立，服务端和客户端之间就可以相互发送数据，直到客户端主动关闭连接。当然，服务端不仅仅只可以让一个客户端进行连接，我们可以尝试让服务端一直运行来不断接受客户端的连接：</p>
<div class="highlight"><pre tabindex="0" class="chroma"><code class="language-java" data-lang="java"><span class="kd">public</span> <span class="kd">static</span> <span class="kt">void</span> <span class="nf">main</span><span class="o">(</span><span class="n">String</span><span class="o">[]</span> <span class="n">args</span><span class="o">)</span> <span class="o">{</span>
    <span class="k">try</span><span class="o">(</span><span class="n">ServerSocket</span> <span class="n">server</span> <span class="o">=</span> <span class="k">new</span> <span class="n">ServerSocket</span><span class="o">(</span><span class="n">8080</span><span class="o">)){</span>    <span class="c1">//将服务端创建在端口8080上
</span><span class="c1"></span>        <span class="n">System</span><span class="o">.</span><span class="na">out</span><span class="o">.</span><span class="na">println</span><span class="o">(</span><span class="s">&#34;正在等待客户端连接...&#34;</span><span class="o">);</span>
        <span class="k">while</span> <span class="o">(</span><span class="kc">true</span><span class="o">){</span>   <span class="c1">//无限循环等待客户端连接
</span><span class="c1"></span>            <span class="n">Socket</span> <span class="n">socket</span> <span class="o">=</span> <span class="n">server</span><span class="o">.</span><span class="na">accept</span><span class="o">();</span>
            <span class="n">System</span><span class="o">.</span><span class="na">out</span><span class="o">.</span><span class="na">println</span><span class="o">(</span><span class="s">&#34;客户端已连接，IP地址为：&#34;</span><span class="o">+</span><span class="n">socket</span><span class="o">.</span><span class="na">getInetAddress</span><span class="o">().</span><span class="na">getHostAddress</span><span class="o">());</span>
        <span class="o">}</span>
    <span class="o">}</span><span class="k">catch</span> <span class="o">(</span><span class="n">IOException</span> <span class="n">e</span><span class="o">){</span>
        <span class="n">e</span><span class="o">.</span><span class="na">printStackTrace</span><span class="o">();</span>
    <span class="o">}</span>
<span class="o">}</span>
</code></pre></div><p>现在我们就可以多次去连接此服务端了。</p>
<h2 id="使用socket进行数据传输">使用Socket进行数据传输</h2>
<p>通过Socket对象，我们就可以获取到对应的I/O流进行网络数据传输：</p>
<div class="highlight"><pre tabindex="0" class="chroma"><code class="language-java" data-lang="java"><span class="kd">public</span> <span class="kd">static</span> <span class="kt">void</span> <span class="nf">main</span><span class="o">(</span><span class="n">String</span><span class="o">[]</span> <span class="n">args</span><span class="o">)</span> <span class="o">{</span>
        <span class="k">try</span> <span class="o">(</span><span class="n">Socket</span> <span class="n">socket</span> <span class="o">=</span> <span class="k">new</span> <span class="n">Socket</span><span class="o">(</span><span class="s">&#34;localhost&#34;</span><span class="o">,</span> <span class="n">8080</span><span class="o">);</span>
             <span class="n">Scanner</span> <span class="n">scanner</span> <span class="o">=</span> <span class="k">new</span> <span class="n">Scanner</span><span class="o">(</span><span class="n">System</span><span class="o">.</span><span class="na">in</span><span class="o">)){</span>
            <span class="n">System</span><span class="o">.</span><span class="na">out</span><span class="o">.</span><span class="na">println</span><span class="o">(</span><span class="s">&#34;已连接到服务端！&#34;</span><span class="o">);</span>
            <span class="n">OutputStream</span> <span class="n">stream</span> <span class="o">=</span> <span class="n">socket</span><span class="o">.</span><span class="na">getOutputStream</span><span class="o">();</span>
            <span class="n">OutputStreamWriter</span> <span class="n">writer</span> <span class="o">=</span> <span class="k">new</span> <span class="n">OutputStreamWriter</span><span class="o">(</span><span class="n">stream</span><span class="o">);</span>  <span class="c1">//通过转换流来帮助我们快速写入内容
</span><span class="c1"></span>            <span class="n">System</span><span class="o">.</span><span class="na">out</span><span class="o">.</span><span class="na">println</span><span class="o">(</span><span class="s">&#34;请输入要发送给服务端的内容：&#34;</span><span class="o">);</span>
            <span class="n">String</span> <span class="n">text</span> <span class="o">=</span> <span class="n">scanner</span><span class="o">.</span><span class="na">nextLine</span><span class="o">();</span>
            <span class="n">writer</span><span class="o">.</span><span class="na">write</span><span class="o">(</span><span class="n">text</span><span class="o">+</span><span class="sc">&#39;\n&#39;</span><span class="o">);</span>   <span class="c1">//因为对方是readLine()这里加个换行符
</span><span class="c1"></span>            <span class="n">writer</span><span class="o">.</span><span class="na">flush</span><span class="o">();</span>
            <span class="n">System</span><span class="o">.</span><span class="na">out</span><span class="o">.</span><span class="na">println</span><span class="o">(</span><span class="s">&#34;数据已发送：&#34;</span><span class="o">+</span><span class="n">text</span><span class="o">);</span>
        <span class="o">}</span><span class="k">catch</span> <span class="o">(</span><span class="n">IOException</span> <span class="n">e</span><span class="o">){</span>
            <span class="n">System</span><span class="o">.</span><span class="na">out</span><span class="o">.</span><span class="na">println</span><span class="o">(</span><span class="s">&#34;服务端连接失败！&#34;</span><span class="o">);</span>
            <span class="n">e</span><span class="o">.</span><span class="na">printStackTrace</span><span class="o">();</span>
        <span class="o">}</span><span class="k">finally</span> <span class="o">{</span>
            <span class="n">System</span><span class="o">.</span><span class="na">out</span><span class="o">.</span><span class="na">println</span><span class="o">(</span><span class="s">&#34;客户端断开连接！&#34;</span><span class="o">);</span>
        <span class="o">}</span>
    <span class="o">}</span>
<span class="o">}</span>
</code></pre></div><div class="highlight"><pre tabindex="0" class="chroma"><code class="language-java" data-lang="java"><span class="kd">public</span> <span class="kd">static</span> <span class="kt">void</span> <span class="nf">main</span><span class="o">(</span><span class="n">String</span><span class="o">[]</span> <span class="n">args</span><span class="o">)</span> <span class="o">{</span>
    <span class="k">try</span><span class="o">(</span><span class="n">ServerSocket</span> <span class="n">server</span> <span class="o">=</span> <span class="k">new</span> <span class="n">ServerSocket</span><span class="o">(</span><span class="n">8080</span><span class="o">)){</span>    <span class="c1">//将服务端创建在端口8080上
</span><span class="c1"></span>        <span class="n">System</span><span class="o">.</span><span class="na">out</span><span class="o">.</span><span class="na">println</span><span class="o">(</span><span class="s">&#34;正在等待客户端连接...&#34;</span><span class="o">);</span>
        <span class="n">Socket</span> <span class="n">socket</span> <span class="o">=</span> <span class="n">server</span><span class="o">.</span><span class="na">accept</span><span class="o">();</span>
        <span class="n">System</span><span class="o">.</span><span class="na">out</span><span class="o">.</span><span class="na">println</span><span class="o">(</span><span class="s">&#34;客户端已连接，IP地址为：&#34;</span><span class="o">+</span><span class="n">socket</span><span class="o">.</span><span class="na">getInetAddress</span><span class="o">().</span><span class="na">getHostAddress</span><span class="o">());</span>
        <span class="n">BufferedReader</span> <span class="n">reader</span> <span class="o">=</span> <span class="k">new</span> <span class="n">BufferedReader</span><span class="o">(</span><span class="k">new</span> <span class="n">InputStreamReader</span><span class="o">(</span><span class="n">socket</span><span class="o">.</span><span class="na">getInputStream</span><span class="o">()));</span>  <span class="c1">//通过
</span><span class="c1"></span>        <span class="n">System</span><span class="o">.</span><span class="na">out</span><span class="o">.</span><span class="na">print</span><span class="o">(</span><span class="s">&#34;接收到客户端数据：&#34;</span><span class="o">);</span>
        <span class="n">System</span><span class="o">.</span><span class="na">out</span><span class="o">.</span><span class="na">println</span><span class="o">(</span><span class="n">reader</span><span class="o">.</span><span class="na">readLine</span><span class="o">());</span>
      	<span class="n">socket</span><span class="o">.</span><span class="na">close</span><span class="o">();</span>   <span class="c1">//和服务端TCP连接完成之后，记得关闭socket
</span><span class="c1"></span>    <span class="o">}</span><span class="k">catch</span> <span class="o">(</span><span class="n">IOException</span> <span class="n">e</span><span class="o">){</span>
        <span class="n">e</span><span class="o">.</span><span class="na">printStackTrace</span><span class="o">();</span>
    <span class="o">}</span>
<span class="o">}</span>
</code></pre></div><p>同理，既然服务端可以读取客户端的内容，客户端也可以在发送后等待服务端给予响应：</p>
<div class="highlight"><pre tabindex="0" class="chroma"><code class="language-java" data-lang="java"><span class="kd">public</span> <span class="kd">static</span> <span class="kt">void</span> <span class="nf">main</span><span class="o">(</span><span class="n">String</span><span class="o">[]</span> <span class="n">args</span><span class="o">)</span> <span class="o">{</span>
    <span class="k">try</span> <span class="o">(</span><span class="n">Socket</span> <span class="n">socket</span> <span class="o">=</span> <span class="k">new</span> <span class="n">Socket</span><span class="o">(</span><span class="s">&#34;localhost&#34;</span><span class="o">,</span> <span class="n">8080</span><span class="o">);</span>
         <span class="n">Scanner</span> <span class="n">scanner</span> <span class="o">=</span> <span class="k">new</span> <span class="n">Scanner</span><span class="o">(</span><span class="n">System</span><span class="o">.</span><span class="na">in</span><span class="o">)){</span>
        <span class="n">System</span><span class="o">.</span><span class="na">out</span><span class="o">.</span><span class="na">println</span><span class="o">(</span><span class="s">&#34;已连接到服务端！&#34;</span><span class="o">);</span>
        <span class="n">OutputStream</span> <span class="n">stream</span> <span class="o">=</span> <span class="n">socket</span><span class="o">.</span><span class="na">getOutputStream</span><span class="o">();</span>
        <span class="n">OutputStreamWriter</span> <span class="n">writer</span> <span class="o">=</span> <span class="k">new</span> <span class="n">OutputStreamWriter</span><span class="o">(</span><span class="n">stream</span><span class="o">);</span>  <span class="c1">//通过转换流来帮助我们快速写入内容
</span><span class="c1"></span>        <span class="n">System</span><span class="o">.</span><span class="na">out</span><span class="o">.</span><span class="na">println</span><span class="o">(</span><span class="s">&#34;请输入要发送给服务端的内容：&#34;</span><span class="o">);</span>
        <span class="n">String</span> <span class="n">text</span> <span class="o">=</span> <span class="n">scanner</span><span class="o">.</span><span class="na">nextLine</span><span class="o">();</span>
        <span class="n">writer</span><span class="o">.</span><span class="na">write</span><span class="o">(</span><span class="n">text</span><span class="o">+</span><span class="sc">&#39;\n&#39;</span><span class="o">);</span>   <span class="c1">//因为对方是readLine()这里加个换行符
</span><span class="c1"></span>        <span class="n">writer</span><span class="o">.</span><span class="na">flush</span><span class="o">();</span>
        <span class="n">System</span><span class="o">.</span><span class="na">out</span><span class="o">.</span><span class="na">println</span><span class="o">(</span><span class="s">&#34;数据已发送：&#34;</span><span class="o">+</span><span class="n">text</span><span class="o">);</span>
        <span class="n">BufferedReader</span> <span class="n">reader</span> <span class="o">=</span> <span class="k">new</span> <span class="n">BufferedReader</span><span class="o">(</span><span class="k">new</span> <span class="n">InputStreamReader</span><span class="o">(</span><span class="n">socket</span><span class="o">.</span><span class="na">getInputStream</span><span class="o">()));</span>
        <span class="n">System</span><span class="o">.</span><span class="na">out</span><span class="o">.</span><span class="na">println</span><span class="o">(</span><span class="s">&#34;收到服务器返回：&#34;</span><span class="o">+</span><span class="n">reader</span><span class="o">.</span><span class="na">readLine</span><span class="o">());</span>
    <span class="o">}</span><span class="k">catch</span> <span class="o">(</span><span class="n">IOException</span> <span class="n">e</span><span class="o">){</span>
        <span class="n">System</span><span class="o">.</span><span class="na">out</span><span class="o">.</span><span class="na">println</span><span class="o">(</span><span class="s">&#34;服务端连接失败！&#34;</span><span class="o">);</span>
        <span class="n">e</span><span class="o">.</span><span class="na">printStackTrace</span><span class="o">();</span>
    <span class="o">}</span><span class="k">finally</span> <span class="o">{</span>
        <span class="n">System</span><span class="o">.</span><span class="na">out</span><span class="o">.</span><span class="na">println</span><span class="o">(</span><span class="s">&#34;客户端断开连接！&#34;</span><span class="o">);</span>
    <span class="o">}</span>
<span class="o">}</span>
</code></pre></div><div class="highlight"><pre tabindex="0" class="chroma"><code class="language-java" data-lang="java"><span class="kd">public</span> <span class="kd">static</span> <span class="kt">void</span> <span class="nf">main</span><span class="o">(</span><span class="n">String</span><span class="o">[]</span> <span class="n">args</span><span class="o">)</span> <span class="o">{</span>
    <span class="k">try</span><span class="o">(</span><span class="n">ServerSocket</span> <span class="n">server</span> <span class="o">=</span> <span class="k">new</span> <span class="n">ServerSocket</span><span class="o">(</span><span class="n">8080</span><span class="o">)){</span>    <span class="c1">//将服务端创建在端口8080上
</span><span class="c1"></span>        <span class="n">System</span><span class="o">.</span><span class="na">out</span><span class="o">.</span><span class="na">println</span><span class="o">(</span><span class="s">&#34;正在等待客户端连接...&#34;</span><span class="o">);</span>
        <span class="n">Socket</span> <span class="n">socket</span> <span class="o">=</span> <span class="n">server</span><span class="o">.</span><span class="na">accept</span><span class="o">();</span>
        <span class="n">System</span><span class="o">.</span><span class="na">out</span><span class="o">.</span><span class="na">println</span><span class="o">(</span><span class="s">&#34;客户端已连接，IP地址为：&#34;</span><span class="o">+</span><span class="n">socket</span><span class="o">.</span><span class="na">getInetAddress</span><span class="o">().</span><span class="na">getHostAddress</span><span class="o">());</span>
        <span class="n">BufferedReader</span> <span class="n">reader</span> <span class="o">=</span> <span class="k">new</span> <span class="n">BufferedReader</span><span class="o">(</span><span class="k">new</span> <span class="n">InputStreamReader</span><span class="o">(</span><span class="n">socket</span><span class="o">.</span><span class="na">getInputStream</span><span class="o">()));</span>  <span class="c1">//通过
</span><span class="c1"></span>        <span class="n">System</span><span class="o">.</span><span class="na">out</span><span class="o">.</span><span class="na">print</span><span class="o">(</span><span class="s">&#34;接收到客户端数据：&#34;</span><span class="o">);</span>
        <span class="n">System</span><span class="o">.</span><span class="na">out</span><span class="o">.</span><span class="na">println</span><span class="o">(</span><span class="n">reader</span><span class="o">.</span><span class="na">readLine</span><span class="o">());</span>
        <span class="n">OutputStreamWriter</span> <span class="n">writer</span> <span class="o">=</span> <span class="k">new</span> <span class="n">OutputStreamWriter</span><span class="o">(</span><span class="n">socket</span><span class="o">.</span><span class="na">getOutputStream</span><span class="o">());</span>
        <span class="n">writer</span><span class="o">.</span><span class="na">write</span><span class="o">(</span><span class="s">&#34;已收到！&#34;</span><span class="o">);</span>
        <span class="n">writer</span><span class="o">.</span><span class="na">flush</span><span class="o">();</span>
    <span class="o">}</span><span class="k">catch</span> <span class="o">(</span><span class="n">IOException</span> <span class="n">e</span><span class="o">){</span>
        <span class="n">e</span><span class="o">.</span><span class="na">printStackTrace</span><span class="o">();</span>
    <span class="o">}</span>
<span class="o">}</span>
</code></pre></div><p>我们可以手动关闭单向的流：</p>
<div class="highlight"><pre tabindex="0" class="chroma"><code class="language-java" data-lang="java"><span class="n">socket</span><span class="o">.</span><span class="na">shutdownOutput</span><span class="o">();</span>  <span class="c1">//关闭输出方向的流
</span><span class="c1"></span><span class="n">socket</span><span class="o">.</span><span class="na">shutdownInput</span><span class="o">();</span>  <span class="c1">//关闭输入方向的流
</span></code></pre></div><p>如果我们不希望服务端等待太长的时间，我们可以通过调用<code>setSoTimeout()</code>方法来设定IO超时时间：</p>
<div class="highlight"><pre tabindex="0" class="chroma"><code class="language-java" data-lang="java"><span class="n">socket</span><span class="o">.</span><span class="na">setSoTimeout</span><span class="o">(</span><span class="n">3000</span><span class="o">);</span>
</code></pre></div><p>当超过设定时间都依然没有收到客户端或是服务端的数据时，会抛出异常：</p>
<div class="highlight"><pre tabindex="0" class="chroma"><code class="language-java" data-lang="java"><span class="n">java</span><span class="o">.</span><span class="na">net</span><span class="o">.</span><span class="na">SocketTimeoutException</span><span class="o">:</span> <span class="n">Read</span> <span class="n">timed</span> <span class="n">out</span>
	<span class="n">at</span> <span class="n">java</span><span class="o">.</span><span class="na">net</span><span class="o">.</span><span class="na">SocketInputStream</span><span class="o">.</span><span class="na">socketRead0</span><span class="o">(</span><span class="n">Native</span> <span class="n">Method</span><span class="o">)</span>
	<span class="n">at</span> <span class="n">java</span><span class="o">.</span><span class="na">net</span><span class="o">.</span><span class="na">SocketInputStream</span><span class="o">.</span><span class="na">socketRead</span><span class="o">(</span><span class="n">SocketInputStream</span><span class="o">.</span><span class="na">java</span><span class="o">:</span><span class="n">116</span><span class="o">)</span>
	<span class="n">at</span> <span class="n">java</span><span class="o">.</span><span class="na">net</span><span class="o">.</span><span class="na">SocketInputStream</span><span class="o">.</span><span class="na">read</span><span class="o">(</span><span class="n">SocketInputStream</span><span class="o">.</span><span class="na">java</span><span class="o">:</span><span class="n">171</span><span class="o">)</span>
	<span class="n">at</span> <span class="n">java</span><span class="o">.</span><span class="na">net</span><span class="o">.</span><span class="na">SocketInputStream</span><span class="o">.</span><span class="na">read</span><span class="o">(</span><span class="n">SocketInputStream</span><span class="o">.</span><span class="na">java</span><span class="o">:</span><span class="n">141</span><span class="o">)</span>
	<span class="n">at</span> <span class="n">sun</span><span class="o">.</span><span class="na">nio</span><span class="o">.</span><span class="na">cs</span><span class="o">.</span><span class="na">StreamDecoder</span><span class="o">.</span><span class="na">readBytes</span><span class="o">(</span><span class="n">StreamDecoder</span><span class="o">.</span><span class="na">java</span><span class="o">:</span><span class="n">284</span><span class="o">)</span>
	<span class="n">at</span> <span class="n">sun</span><span class="o">.</span><span class="na">nio</span><span class="o">.</span><span class="na">cs</span><span class="o">.</span><span class="na">StreamDecoder</span><span class="o">.</span><span class="na">implRead</span><span class="o">(</span><span class="n">StreamDecoder</span><span class="o">.</span><span class="na">java</span><span class="o">:</span><span class="n">326</span><span class="o">)</span>
	<span class="n">at</span> <span class="n">sun</span><span class="o">.</span><span class="na">nio</span><span class="o">.</span><span class="na">cs</span><span class="o">.</span><span class="na">StreamDecoder</span><span class="o">.</span><span class="na">read</span><span class="o">(</span><span class="n">StreamDecoder</span><span class="o">.</span><span class="na">java</span><span class="o">:</span><span class="n">178</span><span class="o">)</span>
	<span class="n">at</span> <span class="n">java</span><span class="o">.</span><span class="na">io</span><span class="o">.</span><span class="na">InputStreamReader</span><span class="o">.</span><span class="na">read</span><span class="o">(</span><span class="n">InputStreamReader</span><span class="o">.</span><span class="na">java</span><span class="o">:</span><span class="n">184</span><span class="o">)</span>
	<span class="n">at</span> <span class="n">java</span><span class="o">.</span><span class="na">io</span><span class="o">.</span><span class="na">BufferedReader</span><span class="o">.</span><span class="na">fill</span><span class="o">(</span><span class="n">BufferedReader</span><span class="o">.</span><span class="na">java</span><span class="o">:</span><span class="n">161</span><span class="o">)</span>
	<span class="n">at</span> <span class="n">java</span><span class="o">.</span><span class="na">io</span><span class="o">.</span><span class="na">BufferedReader</span><span class="o">.</span><span class="na">readLine</span><span class="o">(</span><span class="n">BufferedReader</span><span class="o">.</span><span class="na">java</span><span class="o">:</span><span class="n">324</span><span class="o">)</span>
	<span class="n">at</span> <span class="n">java</span><span class="o">.</span><span class="na">io</span><span class="o">.</span><span class="na">BufferedReader</span><span class="o">.</span><span class="na">readLine</span><span class="o">(</span><span class="n">BufferedReader</span><span class="o">.</span><span class="na">java</span><span class="o">:</span><span class="n">389</span><span class="o">)</span>
	<span class="n">at</span> <span class="n">com</span><span class="o">.</span><span class="na">test</span><span class="o">.</span><span class="na">Main</span><span class="o">.</span><span class="na">main</span><span class="o">(</span><span class="n">Main</span><span class="o">.</span><span class="na">java</span><span class="o">:</span><span class="n">41</span><span class="o">)</span>
</code></pre></div><p>我们之前使用的都是通过构造方法直接连接服务端，那么是否可以等到我们想要的时候再去连接呢？</p>
<div class="highlight"><pre tabindex="0" class="chroma"><code class="language-java" data-lang="java"><span class="k">try</span> <span class="o">(</span><span class="n">Socket</span> <span class="n">socket</span> <span class="o">=</span> <span class="k">new</span> <span class="n">Socket</span><span class="o">();</span> <span class="c1">//调用无参构造不会自动连接
</span><span class="c1"></span>     <span class="n">Scanner</span> <span class="n">scanner</span> <span class="o">=</span> <span class="k">new</span> <span class="n">Scanner</span><span class="o">(</span><span class="n">System</span><span class="o">.</span><span class="na">in</span><span class="o">)){</span> 
    <span class="n">socket</span><span class="o">.</span><span class="na">connect</span><span class="o">(</span><span class="k">new</span> <span class="n">InetSocketAddress</span><span class="o">(</span><span class="s">&#34;localhost&#34;</span><span class="o">,</span> <span class="n">8080</span><span class="o">),</span> <span class="n">1000</span><span class="o">);</span>  <span class="c1">//手动调用connect方法进行连接
</span></code></pre></div><p>如果连接的双方发生意外而通知不到对方，导致一方还持有连接，这样就会占用资源，因此我们可以使用<code>setKeepAlive()</code>方法来防止此类情况发生：</p>
<div class="highlight"><pre tabindex="0" class="chroma"><code class="language-java" data-lang="java"><span class="n">socket</span><span class="o">.</span><span class="na">setKeepAlive</span><span class="o">(</span><span class="kc">true</span><span class="o">);</span>
</code></pre></div><p>当客户端连接后，如果设置了keeplive为 true，当对方没有发送任何数据过来，超过一个时间(看系统内核参数配置)，那么我们这边会发送一个ack探测包发到对方，探测双方的TCP/IP连接是否有效。</p>
<p>TCP在传输过程中，实际上会有一个缓冲区用于数据的发送和接收：</p>
<p><img
        class="lazyload"
        src="/svg/loading.min.svg"
        data-src="https://gimg2.baidu.com/image_search/src=http%3A%2F%2Fpic1.zhimg.com%2Fv2-72f5d4bebca1242a163cbd1ebff3cdbc_b.jpg&amp;refer=http%3A%2F%2Fpic1.zhimg.com&amp;app=2002&amp;size=f9999,10000&amp;q=a80&amp;n=0&amp;g=0n&amp;fmt=jpeg?sec=1637902504&amp;t=2b8dead347f9d2a5bd72e703fc11b987"
        data-srcset="https://gimg2.baidu.com/image_search/src=http%3A%2F%2Fpic1.zhimg.com%2Fv2-72f5d4bebca1242a163cbd1ebff3cdbc_b.jpg&amp;refer=http%3A%2F%2Fpic1.zhimg.com&amp;app=2002&amp;size=f9999%2c10000&amp;q=a80&amp;n=0&amp;g=0n&amp;fmt=jpeg?sec=1637902504&amp;t=2b8dead347f9d2a5bd72e703fc11b987, https://gimg2.baidu.com/image_search/src=http%3A%2F%2Fpic1.zhimg.com%2Fv2-72f5d4bebca1242a163cbd1ebff3cdbc_b.jpg&amp;refer=http%3A%2F%2Fpic1.zhimg.com&amp;app=2002&amp;size=f9999%2c10000&amp;q=a80&amp;n=0&amp;g=0n&amp;fmt=jpeg?sec=1637902504&amp;t=2b8dead347f9d2a5bd72e703fc11b987 1.5x, https://gimg2.baidu.com/image_search/src=http%3A%2F%2Fpic1.zhimg.com%2Fv2-72f5d4bebca1242a163cbd1ebff3cdbc_b.jpg&amp;refer=http%3A%2F%2Fpic1.zhimg.com&amp;app=2002&amp;size=f9999%2c10000&amp;q=a80&amp;n=0&amp;g=0n&amp;fmt=jpeg?sec=1637902504&amp;t=2b8dead347f9d2a5bd72e703fc11b987 2x"
        data-sizes="auto"
        alt="https://gimg2.baidu.com/image_search/src=http%3A%2F%2Fpic1.zhimg.com%2Fv2-72f5d4bebca1242a163cbd1ebff3cdbc_b.jpg&amp;refer=http%3A%2F%2Fpic1.zhimg.com&amp;app=2002&amp;size=f9999,10000&amp;q=a80&amp;n=0&amp;g=0n&amp;fmt=jpeg?sec=1637902504&amp;t=2b8dead347f9d2a5bd72e703fc11b987"
        title="img" /></p>
<p>此缓冲区大小为：8192，我们可以手动调整其大小来优化传输效率：</p>
<div class="highlight"><pre tabindex="0" class="chroma"><code class="language-java" data-lang="java"><span class="n">socket</span><span class="o">.</span><span class="na">setReceiveBufferSize</span><span class="o">(</span><span class="n">25565</span><span class="o">);</span>   <span class="c1">//TCP接收缓冲区
</span><span class="c1"></span><span class="n">socket</span><span class="o">.</span><span class="na">setSendBufferSize</span><span class="o">(</span><span class="n">25565</span><span class="o">);</span>    <span class="c1">//TCP发送缓冲区
</span></code></pre></div><h2 id="使用socket传输文件">使用Socket传输文件</h2>
<p>既然Socket为我们提供了IO流便于数据传输，那么我们就可以轻松地实现文件传输了。</p>
<h2 id="使用浏览器访问socket服务器">使用浏览器访问Socket服务器</h2>
<p>在了解了如何使用Socket传输文件后，我们来看看，浏览器是如何向服务器发起请求的：</p>
<div class="highlight"><pre tabindex="0" class="chroma"><code class="language-java" data-lang="java"><span class="kd">public</span> <span class="kd">static</span> <span class="kt">void</span> <span class="nf">main</span><span class="o">(</span><span class="n">String</span><span class="o">[]</span> <span class="n">args</span><span class="o">)</span> <span class="o">{</span>
        <span class="k">try</span><span class="o">(</span><span class="n">ServerSocket</span> <span class="n">server</span> <span class="o">=</span> <span class="k">new</span> <span class="n">ServerSocket</span><span class="o">(</span><span class="n">8080</span><span class="o">)){</span>    <span class="c1">//将服务端创建在端口8080上
</span><span class="c1"></span>            <span class="n">System</span><span class="o">.</span><span class="na">out</span><span class="o">.</span><span class="na">println</span><span class="o">(</span><span class="s">&#34;正在等待客户端连接...&#34;</span><span class="o">);</span>
            <span class="n">Socket</span> <span class="n">socket</span> <span class="o">=</span> <span class="n">server</span><span class="o">.</span><span class="na">accept</span><span class="o">();</span>
            <span class="n">System</span><span class="o">.</span><span class="na">out</span><span class="o">.</span><span class="na">println</span><span class="o">(</span><span class="s">&#34;客户端已连接，IP地址为：&#34;</span><span class="o">+</span><span class="n">socket</span><span class="o">.</span><span class="na">getInetAddress</span><span class="o">().</span><span class="na">getHostAddress</span><span class="o">());</span>
            <span class="n">InputStream</span> <span class="n">in</span> <span class="o">=</span> <span class="n">socket</span><span class="o">.</span><span class="na">getInputStream</span><span class="o">();</span>  <span class="c1">//通过
</span><span class="c1"></span>            <span class="n">System</span><span class="o">.</span><span class="na">out</span><span class="o">.</span><span class="na">println</span><span class="o">(</span><span class="s">&#34;接收到客户端数据：&#34;</span><span class="o">);</span>
            <span class="k">while</span> <span class="o">(</span><span class="kc">true</span><span class="o">){</span>
                <span class="kt">int</span> <span class="n">i</span> <span class="o">=</span> <span class="n">in</span><span class="o">.</span><span class="na">read</span><span class="o">();</span>
                <span class="k">if</span><span class="o">(</span><span class="n">i</span> <span class="o">==</span> <span class="o">-</span><span class="n">1</span><span class="o">)</span> <span class="k">break</span><span class="o">;</span>
                <span class="n">System</span><span class="o">.</span><span class="na">out</span><span class="o">.</span><span class="na">print</span><span class="o">((</span><span class="kt">char</span><span class="o">)</span> <span class="n">i</span><span class="o">);</span>
            <span class="o">}</span>
        <span class="o">}</span><span class="k">catch</span> <span class="o">(</span><span class="n">Exception</span> <span class="n">e</span><span class="o">){</span>
            <span class="n">e</span><span class="o">.</span><span class="na">printStackTrace</span><span class="o">();</span>
        <span class="o">}</span>
    <span class="o">}</span>
</code></pre></div><p>我们现在打开浏览器，输入http://localhost:8080或是http://127.0.0.1:8080/，来连接我们本地开放的服务器。</p>
<p>我们发现浏览器是无法打开这个链接的，但是我们服务端却收到了不少的信息：</p>
<pre><code class="language-properties" data-lang="properties">GET / HTTP/1.1
Host: 127.0.0.1:8080
Connection: keep-alive
Cache-Control: max-age=0
sec-ch-ua: &quot;Chromium&quot;;v=&quot;94&quot;, &quot;Google Chrome&quot;;v=&quot;94&quot;, &quot;;Not A Brand&quot;;v=&quot;99&quot;
sec-ch-ua-mobile: ?0
sec-ch-ua-platform: &quot;macOS&quot;
Upgrade-Insecure-Requests: 1
User-Agent: Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/94.0.4606.81 Safari/537.36
Accept: text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3;q=0.9
Sec-Fetch-Site: none
Sec-Fetch-Mode: navigate
Sec-Fetch-User: ?1
Sec-Fetch-Dest: document
Accept-Encoding: gzip, deflate, br
Accept-Language: zh-CN,zh;q=0.9,und;q=0.8,en;q=0.7
</code></pre><p>实际上这些内容都是Http协议规定的请求头内容。HTTP是一种应用层协议，全称为超文本传输协议，它本质也是基于TCP协议进行数据传输，因此我们的服务端能够读取HTTP请求。但是Http协议并不会保持长连接，在得到我们响应的数据后会立即关闭TCP连接。</p>
<p>既然使用的是Http连接，如果我们的服务器要支持响应HTTP请求，那么就需要按照HTTP协议的规则，返回一个规范的响应文本，首先是响应头，它至少要包含一个响应码：</p>
<pre><code class="language-properties" data-lang="properties">HTTP/1.1 200 Accpeted
</code></pre><p>然后就是响应内容（注意一定要换行再写），我们尝试来编写一下支持HTTP协议的响应内容：</p>
<div class="highlight"><pre tabindex="0" class="chroma"><code class="language-java" data-lang="java"><span class="kd">public</span> <span class="kd">static</span> <span class="kt">void</span> <span class="nf">main</span><span class="o">(</span><span class="n">String</span><span class="o">[]</span> <span class="n">args</span><span class="o">)</span> <span class="o">{</span>
    <span class="k">try</span><span class="o">(</span><span class="n">ServerSocket</span> <span class="n">server</span> <span class="o">=</span> <span class="k">new</span> <span class="n">ServerSocket</span><span class="o">(</span><span class="n">8080</span><span class="o">)){</span>    <span class="c1">//将服务端创建在端口8080上
</span><span class="c1"></span>        <span class="n">System</span><span class="o">.</span><span class="na">out</span><span class="o">.</span><span class="na">println</span><span class="o">(</span><span class="s">&#34;正在等待客户端连接...&#34;</span><span class="o">);</span>
        <span class="n">Socket</span> <span class="n">socket</span> <span class="o">=</span> <span class="n">server</span><span class="o">.</span><span class="na">accept</span><span class="o">();</span>
        <span class="n">System</span><span class="o">.</span><span class="na">out</span><span class="o">.</span><span class="na">println</span><span class="o">(</span><span class="s">&#34;客户端已连接，IP地址为：&#34;</span><span class="o">+</span><span class="n">socket</span><span class="o">.</span><span class="na">getInetAddress</span><span class="o">().</span><span class="na">getHostAddress</span><span class="o">());</span>
        <span class="n">BufferedReader</span> <span class="n">reader</span> <span class="o">=</span> <span class="k">new</span> <span class="n">BufferedReader</span><span class="o">(</span><span class="k">new</span> <span class="n">InputStreamReader</span><span class="o">(</span><span class="n">socket</span><span class="o">.</span><span class="na">getInputStream</span><span class="o">()));</span>  <span class="c1">//通过
</span><span class="c1"></span>        <span class="n">System</span><span class="o">.</span><span class="na">out</span><span class="o">.</span><span class="na">println</span><span class="o">(</span><span class="s">&#34;接收到客户端数据：&#34;</span><span class="o">);</span>
        <span class="k">while</span> <span class="o">(</span><span class="n">reader</span><span class="o">.</span><span class="na">ready</span><span class="o">())</span> <span class="n">System</span><span class="o">.</span><span class="na">out</span><span class="o">.</span><span class="na">println</span><span class="o">(</span><span class="n">reader</span><span class="o">.</span><span class="na">readLine</span><span class="o">());</span>   <span class="c1">//ready是判断当前流中是否还有可读内容
</span><span class="c1"></span>        <span class="n">OutputStreamWriter</span> <span class="n">writer</span> <span class="o">=</span> <span class="k">new</span> <span class="n">OutputStreamWriter</span><span class="o">(</span><span class="n">socket</span><span class="o">.</span><span class="na">getOutputStream</span><span class="o">());</span>
        <span class="n">writer</span><span class="o">.</span><span class="na">write</span><span class="o">(</span><span class="s">&#34;HTTP/1.1 200 Accepted\r\n&#34;</span><span class="o">);</span>   <span class="c1">//200是响应码，Http协议规定200为接受请求，400为错误的请求，404为找不到此资源（不止这些，还有很多）
</span><span class="c1"></span>        <span class="n">writer</span><span class="o">.</span><span class="na">write</span><span class="o">(</span><span class="s">&#34;\r\n&#34;</span><span class="o">);</span>   <span class="c1">//在请求头写完之后还要进行一次换行，然后写入我们的响应实体（会在浏览器上展示的内容）
</span><span class="c1"></span>        <span class="n">writer</span><span class="o">.</span><span class="na">write</span><span class="o">(</span><span class="s">&#34;lbwnb!&#34;</span><span class="o">);</span>
        <span class="n">writer</span><span class="o">.</span><span class="na">flush</span><span class="o">();</span>
    <span class="o">}</span><span class="k">catch</span> <span class="o">(</span><span class="n">Exception</span> <span class="n">e</span><span class="o">){</span>
        <span class="n">e</span><span class="o">.</span><span class="na">printStackTrace</span><span class="o">();</span>
    <span class="o">}</span>
<span class="o">}</span>
</code></pre></div><p>我们可以打开浏览器的开发者模式（这里推荐使用Chrome/Edge浏览器，按下F12即可打开），我们来观察一下浏览器的实际请求过程。</p>
</div><div class="post-footer" id="post-footer">
    <div class="post-info"><div class="post-info-tag"><span><a href="/tags/javaweb%E7%AC%AC%E4%B8%80%E8%8A%82/">JavaWeb第一节</a>
                </span></div><div class="post-info-line"><div class="post-info-mod">
                <span>更新于 2022-01-26</span>
            </div><div class="post-info-mod"></div>
        </div><div class="post-info-share">
            <span><a href="javascript:void(0);" title="分享到 Twitter" data-sharer="twitter" data-url="https://acking-you.github.io/posts/java%E7%BD%91%E7%BB%9C%E7%BC%96%E7%A8%8B/" data-title="Java网络编程" data-hashtags="JavaWeb第一节"><i class="fab fa-twitter fa-fw"></i></a><a href="javascript:void(0);" title="分享到 Facebook" data-sharer="facebook" data-url="https://acking-you.github.io/posts/java%E7%BD%91%E7%BB%9C%E7%BC%96%E7%A8%8B/" data-hashtag="JavaWeb第一节"><i class="fab fa-facebook-square fa-fw"></i></a><a href="javascript:void(0);" title="分享到 WhatsApp" data-sharer="whatsapp" data-url="https://acking-you.github.io/posts/java%E7%BD%91%E7%BB%9C%E7%BC%96%E7%A8%8B/" data-title="Java网络编程" data-web><i class="fab fa-whatsapp fa-fw"></i></a><a href="javascript:void(0);" title="分享到 Line" data-sharer="line" data-url="https://acking-you.github.io/posts/java%E7%BD%91%E7%BB%9C%E7%BC%96%E7%A8%8B/" data-title="Java网络编程"><i class="fab fa-line fa-fw"></i></a><a href="javascript:void(0);" title="分享到 微博" data-sharer="weibo" data-url="https://acking-you.github.io/posts/java%E7%BD%91%E7%BB%9C%E7%BC%96%E7%A8%8B/" data-title="Java网络编程" data-image="https://s4.ax1x.com/2022/01/22/7hWvAH.png"><i class="fab fa-weibo fa-fw"></i></a><a href="javascript:void(0);" title="分享到 Myspace" data-sharer="myspace" data-url="https://acking-you.github.io/posts/java%E7%BD%91%E7%BB%9C%E7%BC%96%E7%A8%8B/" data-title="Java网络编程" data-description="Java网络编程"><i data-svg-src="/lib/simple-icons/icons/myspace.min.svg"></i></a><a href="javascript:void(0);" title="分享到 Blogger" data-sharer="blogger" data-url="https://acking-you.github.io/posts/java%E7%BD%91%E7%BB%9C%E7%BC%96%E7%A8%8B/" data-title="Java网络编程" data-description="Java网络编程"><i class="fab fa-blogger fa-fw"></i></a><a href="javascript:void(0);" title="分享到 Evernote" data-sharer="evernote" data-url="https://acking-you.github.io/posts/java%E7%BD%91%E7%BB%9C%E7%BC%96%E7%A8%8B/" data-title="Java网络编程"><i class="fab fa-evernote fa-fw"></i></a></span>
        </div></div><div class="post-nav"><a href="/posts/tcp%E7%BD%91%E7%BB%9C%E7%BC%96%E7%A8%8B%E4%B8%ADconnectlistenaccept%E4%B8%89%E8%80%85%E4%B9%8B%E9%97%B4%E7%9A%84%E5%85%B3%E7%B3%BB/" class="prev" rel="prev" title="TCP网络编程中connect、listen、accept三者之间的关系"><i class="fas fa-angle-left fa-fw"></i>Previous Post</a>
            <a href="/posts/leetcode%E6%AF%8F%E6%97%A5%E4%B8%80%E9%A2%98-%E6%A3%80%E6%B5%8B%E6%AD%A3%E6%96%B9%E5%BD%A2/" class="next" rel="next" title="leetcode每日一题-检测正方形">Next Post<i class="fas fa-angle-right fa-fw"></i></a></div></div>
</div></article></div>
            </main>
            <footer class="footer"><div class="footer-container"><div class="footer-line">由 <a href="https://gohugo.io/" target="_blank" rel="noopener noreffer" title="Hugo 0.86.0">Hugo</a> 强力驱动 | 主题 - <a href="https://github.com/khusika/FeelIt" target="_blank" rel="noopener noreffer" title="FeelIt 1.0.1"><i class="fas fa-hand-holding-heart fa-fw"></i> FeelIt</a>
        </div><div class="footer-line" itemscope itemtype="http://schema.org/CreativeWork"><i class="far fa-copyright fa-fw"></i><span itemprop="copyrightYear">2023</span><span class="author" itemprop="copyrightHolder">&nbsp;<a href="/"></a></span></div>
</div>
</footer>
        </div>

        <div id="fixed-buttons"><a href="#" id="back-to-top" class="fixed-button" title="回到顶部">
                <i class="fas fa-chevron-up fa-fw"></i>
            </a></div><link rel="stylesheet" href="/lib/fontawesome-free/all.min.css"><link rel="stylesheet" href="/lib/animate/animate.min.css"><link rel="stylesheet" href="/lib/katex/katex.min.css"><link rel="stylesheet" href="/lib/katex/copy-tex.min.css"><script src="/lib/autocomplete/autocomplete.min.js"></script><script src="/lib/lunr/lunr.min.js"></script><script src="/lib/lunr/lunr.stemmer.support.min.js"></script><script src="/lib/lunr/lunr.zh.min.js"></script><script src="/lib/lazysizes/lazysizes.min.js"></script><script src="/lib/clipboard/clipboard.min.js"></script><script src="/lib/sharer/sharer.min.js"></script><script src="/lib/katex/katex.min.js"></script><script src="/lib/katex/auto-render.min.js"></script><script src="/lib/katex/copy-tex.min.js"></script><script src="/lib/katex/mhchem.min.js"></script><script>window.config={"code":{"copyTitle":"复制到剪贴板","maxShownLines":200},"comment":{},"math":{"delimiters":[{"display":true,"left":"$$","right":"$$"},{"display":true,"left":"\\[","right":"\\]"},{"display":false,"left":"$","right":"$"},{"display":false,"left":"\\(","right":"\\)"}],"strict":false},"search":{"highlightTag":"em","lunrIndexURL":"/index.json","lunrLanguageCode":"zh","lunrSegmentitURL":"/lib/lunr/lunr.segmentit.js","maxResultLength":100,"noResultsFound":"没有找到结果","snippetLength":50,"type":"lunr"}};</script><script src="/js/theme.min.js"></script></body></html>
